import React from 'react';
import { Link } from 'react-router-dom';
import Axios from 'axios';
import { apiPrefix } from 'shared/api';
import Td from './TableTr';


class Projects extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      projects: [],
      newProject: {},
      show: false,
    };
  }
  componentDidMount() {
    const api = `${apiPrefix}api/v1/unirole/projects`;
    Axios.get(api)
      .then((response) => {
        this.setState({ projects: response.data.data });
        console.log(this.state.projects);
      });
  }
  showAddInput=() => {
    this.setState({ show: true });
  }
  handleOnChange=(value, key) => {
    const { newProject } = this.state;
    newProject[key] = value;
    this.setState({ newProject: { ...this.state.newProject } });
  }
  addnewProject=() => {
    const { newProject } = this.state;
    const api = `${apiPrefix}api/v1/unirole/project`;
    Axios.post(api, newProject)
      .then((response) => {
        console.log(response);
        this.componentDidMount();
      });
  }
  sureEdit=(val) => {
    const api = `${apiPrefix}api/v1/unirole/project`;
    Axios.put(api, val)
      .then((response) => {
        console.log(response.status === 200);
        if (response.status === 200) {
          this.componentDidMount();
        }
      });
  }
  render() {
    const { newProject, show, projects } = this.state;
    return (
      <div className="content">
        <div>
          <h3>项目管理</h3>
          <table style={{ width: '98%' }}>
            <thead>
              <tr>
                <th>序号</th>
                <th>项目名称</th>
                <th><button className="addButton" onClick={this.showAddInput}>添加</button></th>
              </tr>
            </thead>
            <tbody>
              <tr className={show ? 'add-contract-type' : 'hide'}>
                <td />
                <td>
                  <input
                    value={newProject.name || ''}
                    type="text"
                    onChange={e => this.handleOnChange(e.target.value, 'name')}
                  />
                </td>
                <td>
                  <button className="green-button" onClick={this.addnewProject}>保存</button>
                  <button className="clearButton" onClick={this.cancelAdd}>取消</button>
                </td>
              </tr>
              {
              projects.map((value, index) => (
                <tr key={index}>
                  <Td
                    sureEdit={val => this.sureEdit(val)}
                    value={value}
                    index={index}
                  />
                </tr>
              ))
            }
            </tbody>
          </table>
        </div>
      </div>
    );
  }
}

export default Projects;
